<!--
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-03 14:41:20
 * @LastEditTime: 2023-08-31 11:00:35
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description:   :gridOps="gridOptions" other
-->

<template>
  <el-container>
    <el-aside width="250px" class="nosche">
      <div class="sticky-form">
        <el-form
          :label-position="'top'"
          label-width="auto"
          :model="search"
          style="background-color: rgb(177 216 255)"
        >
          <el-row>
            <el-col :span="8">
              <el-form-item label="搜索客户" style="margin: 0">
                <el-input v-model="search.customer"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="搜索品名" style="margin: 0">
                <el-input v-model="search.material"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="搜索点棍" style="margin: 0">
                <el-input v-model="search.point_stick"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <draggable
        class="list-group"
        group="task"
        v-model="need_scheduling"
        item-key="id"
        ghost-class="ghost"
        @update="dragend"
        @add="dragend"
      >
        <template #item="{ element }">
          <li class="spandata">
            {{ element.code }} {{ element.material }} {{ element.quantity }}
            <br />
            {{ element.color_name }} {{ element.dyelot }}
            <br />
            {{ element.process_route.name }}
            |
            {{ element.process_name }}
            <br />
            {{ element.bom }}
          </li>
        </template>
      </draggable>
      <div class="pagination-bar">
        <div class="page-info">
          <span class="current">第{{ currentPage }}页</span>
          <span class="separator">/</span>
          <span class="total">共{{ totalPages }}页</span>
        </div>

        <div class="button-group">
          <el-button
            :disabled="currentPage <= 1"
            @click="handlePageChange(-1)"
            :icon="'ArrowLeft'"
            class="pagination-btn prev-btn"
          >
            上一页
          </el-button>

          <el-button
            :disabled="currentPage >= totalPages"
            @click="handlePageChange(1)"
            class="pagination-btn next-btn"
          >
            下一页
            <el-icon><ArrowRight /></el-icon>
          </el-button>
        </div>
      </div>
    </el-aside>
    <el-main
      ><div class="proscheduling">
        <sc-VxeTable
          ref="xGrid"
          :gridEvts="gridEvents"
          :gridOps="gridOps"
          :tablecode="'pro_scheduing_index'"
          :data="details"
        >
          <template #time-line>
            <div
              class="timeline"
              style="border-radius: 5px; box-shadow: rgba(0, 0, 0, 0.15) 0px 1px 3px 0px"
            >
              <div class="hours">
                <span
                  :title="item.date"
                  class="hour-item"
                  style="width: 88px"
                  v-for="(item, index) in date"
                  v-bind:key="index"
                >
                  {{ item.time }} <span class="data">{{ item.date }}</span>
                </span>
              </div>
              <div class="ticks">
                <span
                  v-for="index in 80 * 4"
                  :class="'tk ' + ((index - 1) % 4 == 0 ? 'long' : '')"
                  :style="'left:' + ((index - 1) * 22 + 44) + 'px'"
                  v-bind:key="index"
                ></span>
              </div>
            </div>
          </template>
        </sc-VxeTable></div
    ></el-main>
  </el-container>
</template>

<script>
export default {
  name: "pro_scheduing",
};
</script>

<script setup>
import { VXETable } from "vxe-table";

import { nextTick, ref, onMounted, onBeforeUnmount, watch } from "vue";
import api from "@/api";
import tool from "@/utils/tool";
import draggable from "vuedraggable";
import formatterScheduling from "./formatterScheduling.vue";

VXETable.renderer.add("formatterScheduling", {
  // 默认显示模板
  renderDefault(renderOpts, params) {
    return (
      <formatterScheduling
        params={params}
        success={handleSuccess}
        renderOpts={renderOpts}
      ></formatterScheduling>
    );
  },
});

const search = ref({ point_stick: "", material: "", customer: "" });
const date = ref([]);
const xGrid = ref({});
const details = ref([]);
const need_scheduling = ref([]);
// 保持原有逻辑不变，新增视觉状态

const handleSuccess = () => {
  getData();
};
const gridOps = {
  rowConfig: {
    height: 60,
  },
  columns: [
    {
      field: "open_card_details_scheduling",
      slots: {
        header: "time-line",
      },
      getcolDate() {
        return datetime;
      },
      showOverflow: "ellipsis",
    },
    {
      field: "name",
    },
  ],
};
const dragend = a => {
  api.pro.OpenCard.sort
    .post({
      machine_id: 0,
      open_card_ids: need_scheduling.value.map(v => v.id),
    })
    .then(() => {
      getData();
    });
};
const need_scheduling_filter = ref({});
watch(
  () => search.value,
  value => {
    let filter = [];
    let st = value.point_stick.trim();
    let mt = value.material.trim();
    let cu = value.customer.trim();
    if (st != "") {
      filter.push({ "point_stick.name": { type: "lk", value: st } });
    }
    if (mt != "") {
      filter.push({ "open_card_details.custno": { type: "lk", value: mt } });
    }
    if (cu != "") {
      filter.push({ "customer.code": { type: "lk", value: cu } });
    }
    need_scheduling_filter.value = filter;
    getNeedSch();
  },
  {
    deep: true,
  }
);
const currentPage = ref(1);
const totalPages = ref(0);
const pageSize = 40;
const handlePageChange = page => {
  currentPage.value += parseInt(page);
  getNeedSch();
};

const getNeedSch = () => {
  let params = {
    filter: need_scheduling_filter.value,
    page: currentPage.value,
    pageSize: pageSize.value,
  };
  api.pro.scheduling.get_need_scheduling.get(params).then(res => {
    currentPage.value = parseInt(res.data.page);
    totalPages.value = Math.ceil(res.data.total / pageSize);
    let permin_width = 22 / 15;
    need_scheduling.value = res.data.rows.map(open_card => {
      let min = open_card.quantity / 15;
      min = min < 60 ? 60 : min;
      let width = min * permin_width;
      return {
        id: open_card.id,
        quantity: open_card.open_card_details.quantity,
        datetime: open_card.audited_at ?? open_card.created_at,
        width: width,
        code: open_card.customer.code,
        open_card: open_card.open_card_details.code,
        material: open_card.open_card_details.custno,
        color_name: open_card.open_card_details.color_name,
        dyelot: open_card.open_card_details.dyelot,
        process_name: open_card.process_name,
        process_route: open_card.process_route,
        bom:
          (open_card.point_stick?.name ?? "") +
          " | " +
          (open_card.glue?.name ?? "") +
          " | " +
          (open_card.material?.name ?? ""),

        value:
          open_card.material?.name + " | " + open_card.quantity + " | " + open_card.code,
      };
    });
  });
};
const getData = () => {
  api.pro.scheduling.list.get({ sort: "sort", order: "asc" }).then(res => {
    if (res) {
      details.value = res.data.rows;
      afterQuery(res);
    }
  });
};

const timeInterval = ref(0);
onMounted(() => {
  clearInterval(timeInterval.value);
  timeInterval.value = setInterval(() => {
    // 刷新页面的逻辑，例如重新加载数据
    nextTick(() => {
      getData();
    });
  }, 15000); // 每5000毫秒（5秒）执行一次
  getData();
  getNeedSch();
});
onBeforeUnmount(() => {
  clearInterval(timeInterval.value);
});
const datetime = ref(null);
const scrollToNowTime = function () {
  let nowtime = new Date().getTime();
  if (nowtime - datetime.value - 3 * 60 * 60 * 1000 > 0) {
    let widthtoscll =
      ((nowtime - datetime.value - 3 * 60 * 60 * 1000) / 1000 / 60 / 60) * 4 * 22;
    setTimeout(() => {
      xGrid.value.xGrid.scrollTo(widthtoscll, 0);
    }, 100);
  }
};
const afterQuery = res => {
  if (datetime.value == null || datetime.value != new Date(res.data.date).getTime()) {
    datetime.value = new Date(res.data.date).getTime();
    let dateArray = [];
    let ymd = "";
    for (
      let times = datetime.value;
      times <= datetime.value + 80 * 60 * 60 * 1000;
      times = times + 60 * 60 * 1000
    ) {
      let showymd = "";
      if (ymd != tool.dateFormat(times, "yyyy-MM-dd")) {
        ymd = showymd = tool.dateFormat(times, "yyyy-MM-dd");
      }
      dateArray.push({
        date: showymd,
        time: tool.dateFormat(times, "hh:mm"),
      });
    }
    date.value = dateArray;
    scrollToNowTime();
  }
};
const gridEvents = {
  scrollToNow: function () {
    scrollToNowTime();
  },
};
</script>
<style>
.proscheduling {
  height: 100%;
}

.nosche .spandata {
  display: block;
  height: 80px;
  overflow: hidden;
  font-size: 12px;
  text-overflow: ellipsis;
  background-color: rgb(220, 238, 255);
  cursor: grab;
  line-height: 20px;
  overflow: hidden;
  width: "190px";
  margin-top: 5px;
  border-bottom: 1px solid rgb(230, 226, 226);
}
.proscheduling .timeline {
  margin-top: 15px;
  white-space: nowrap;
  text-align: left;
}
.proscheduling .hour-item {
  position: relative;
  display: inline-block;
  font-size: 14px;
  line-height: 25px;
  text-align: center;
  transition: all 0.2s ease 0s;
  white-space: nowrap;
}
.proscheduling .data {
  position: absolute;
  top: -20px;
  left: 50%;
  white-space: nowrap;
  transition: all 0.2s ease 0s;
  transform: translateX(-50%);
}
.proscheduling .ticks {
  position: relative;
  margin-top: 5px;
  white-space: nowrap;
  border-bottom: 1px solid rgb(234, 234, 234);
  transition: all 0.2s ease 0s;
}
.proscheduling .tk {
  position: absolute;
  bottom: 0px;
  width: 1px;
  height: 5px;
  background: rgb(182, 182, 182);
}
.proscheduling .long {
  height: 8px;
}
.sticky-form {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
  padding: 1px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  margin-bottom: 2px;
}
.sticky-nav-btns {
  position: sticky;
  bottom: 0;
  z-index: 100;
  padding: 0 16px 20px;
  margin-top: auto; /* 关键布局属性 */
  backdrop-filter: blur(8px);
}

.custom-aside {
  --primary-color: #6366f1;
  --bg-color: #ffffff;
  --shadow-color: rgba(99, 102, 241, 0.1);
  height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content-area {
  flex: 1;
  overflow: hidden;
}

.pagination-bar {
  position: sticky;
  bottom: 0;
  background: rgb(220, 238, 255);
  padding: 0;
  box-shadow: 0 -3px 24px rgb(255, 238, 255);
  border-top: 1px solid #f3f4f6;
}

.page-info {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 6px;
  font-size: 14px;
  color: #6b7280;
}

.current {
  font-weight: 600;
  margin: 0 4px;
}

.separator {
  margin: 0 2px;
}

.button-group {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}

.pagination-btn {
  height: 34px;
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb !important;
}

.pagination-btn:hover:not(.is-disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px var(--shadow-color);
}

.pagination-btn:active:not(.is-disabled) {
  transform: translateY(0);
}

.pagination-btn.is-disabled {
  opacity: 0.6;
  filter: grayscale(0.8);
}

@media (max-width: 768px) {
  .pagination-bar {
    padding: 16px;
  }

  .pagination-btn {
    font-size: 14px;
    padding: 0 12px;
  }

  .current {
    font-size: 16px;
  }
}
</style>
